package Pool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
    private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();//任务队列
    public MyThreadPool(int poolSize){
        for (int i = 0; i < poolSize; i++) {
            Thread thread = new Thread(() -> {
                try {
                    while (true){
                        Runnable task = queue.take();
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            thread.setDaemon(true);
            thread.start();
        }
    }
    //将任务提交到任务队列中
    public void submit(Runnable task) throws InterruptedException {
        queue.put(task);
    }
}
class MyTest{
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(4);
        for (int i = 0; i < 1000; i++) {
            final int id = i;
            myThreadPool.submit(() ->{
                String name = Thread.currentThread().getName();
                System.out.println(name + "-" + id);
            });
        }
        Thread.sleep(1000);
    }
}
